package ua.com.infinite.mobile.db;

import java.util.ArrayList;
import java.util.LinkedList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ua.com.infinite.mobile.App;
import ua.com.infinite.mobile.contentprovider.InfiniteContentProvider;
import ua.com.infinite.mobile.plains.NewsItem;
import ua.com.infinite.mobile.plains.Transaktion;
import ua.com.infinite.mobile.plains.User;
import ua.com.infinite.mobile.server.RequestObject;
import ua.com.infinite.mobile.server.ResponseObject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBAdapter extends SQLiteOpenHelper {

	public static String DB_NAME = "inf_club.db";
	public static int DB_VERSION = 2;

	private SQLiteDatabase db;
	private Context context;

	public DBAdapter(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		TableUser.onCreate(db);
		TableNews.onCreate(db);
		TableTransaktions.onCreate(db);

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + TableUser.TABLE_NAME);
		db.execSQL("DROP TABLE IF EXISTS " + TableNews.TABLE_NAME);
		db.execSQL("DROP TABLE IF EXISTS " + TableTransaktions.TABLE_NAME);

	}

	public JSONObject getUser(int id) {
		JSONObject result = new JSONObject();
		Cursor user = context.getContentResolver().query(InfiniteContentProvider.CONTENT_URI_USERS, null, TableUser.COLUMN_ID + "=" + id, null, null);
		if (user != null && user.moveToFirst()) {
			try {
				result.put(User.USER_ID, user.getInt(user.getColumnIndex(TableUser.COLUMN_ID)));
				result.put(User.USER_SESSION, user.getString(user.getColumnIndex(TableUser.COLUMN_SESSION)));
				result.put(User.USER_AVATAR, user.getString(user.getColumnIndex(TableUser.COLUMN_AVATAR)));
				result.put(User.USER_FIRST_NAME, user.getString(user.getColumnIndex(TableUser.COLUMN_FIRST_NAME)));
				result.put(User.USER_LASR_NAME, user.getString(user.getColumnIndex(TableUser.COLUMN_LAST_NAME)));
				result.put(User.USER_BALLANCE, user.getString(user.getColumnIndex(TableUser.COLUMN_BALLANCE)));
				result.put(User.USER_EMAIL, user.getString(user.getColumnIndex(TableUser.COLUMN_EMAIL)));
				result.put(User.USER_PHONE, user.getString(user.getColumnIndex(TableUser.COLUMN_PHONE)));
				String accountString = user.getString(user.getColumnIndex(TableUser.COLUMN_ACCOUNTS));
				JSONArray accounts = new JSONArray();
				if (!accountString.equals("")) {
					String[] accounts_array = user.getString(user.getColumnIndex(TableUser.COLUMN_ACCOUNTS)).split("\\|");
					if (accounts_array.length > 0) {
						for (int i = 0; i < accounts_array.length; i++) {
							accounts.put(accounts_array[i]);
						}
					}
				}
				result.put(User.USER_ACCOUNTS, accounts);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		user.close();

		return result;
	}

	public void createOrUpdate(JSONObject object) {
		int user_id = 0;
		try {
			user_id = object.getInt(User.USER_ID);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		Cursor user = context.getContentResolver().query(InfiniteContentProvider.CONTENT_URI_USERS, null, TableUser.COLUMN_ID + "=" + user_id, null,
				null);
		if (user != null && user.moveToFirst()) {
			updateUser(object);
		} else {
			createUser(object);
		}
		user.close();

	}

	public void createUser(JSONObject object) {
		ContentValues values = new ContentValues();
		try {
			values.put(TableUser.COLUMN_ID, object.getInt(User.USER_ID));
			values.put(TableUser.COLUMN_SESSION, object.getString(User.USER_SESSION));
			values.put(TableUser.COLUMN_AVATAR, object.getString(User.USER_AVATAR));
			values.put(TableUser.COLUMN_FIRST_NAME, object.getString(User.USER_FIRST_NAME));
			values.put(TableUser.COLUMN_LAST_NAME, object.getString(User.USER_LASR_NAME));
			values.put(TableUser.COLUMN_BALLANCE, object.getString(User.USER_BALLANCE));
			values.put(TableUser.COLUMN_EMAIL, object.getString(User.USER_EMAIL));
			values.put(TableUser.COLUMN_PHONE, object.getString(User.USER_PHONE));

			JSONArray accounts_array = object.getJSONArray(User.USER_ACCOUNTS);
			if (accounts_array.length() == 0) {
				values.put(TableUser.COLUMN_ACCOUNTS, "");
			} else {
				String accounts = "";
				for (int i = 0; i < accounts_array.length(); i++) {
					accounts += accounts_array.getString(i);
					if (i < accounts_array.length() - 1) {
						accounts += "|";
					}
				}
				values.put(TableUser.COLUMN_ACCOUNTS, accounts);
			}

			values.put(TableUser.COLUMN_DATE, "dare");
		} catch (JSONException e) {
			e.printStackTrace();
			return;
		}
		context.getContentResolver().insert(InfiniteContentProvider.CONTENT_URI_USERS, values);
	}

	public void updateUser(JSONObject object) {
		ContentValues values = new ContentValues();
		int user_id = 0;
		try {
			user_id = object.getInt(User.USER_ID);
			values.put(TableUser.COLUMN_SESSION, object.getString(User.USER_SESSION));
			values.put(TableUser.COLUMN_AVATAR, object.getString(User.USER_AVATAR));
			values.put(TableUser.COLUMN_FIRST_NAME, object.getString(User.USER_FIRST_NAME));
			values.put(TableUser.COLUMN_LAST_NAME, object.getString(User.USER_LASR_NAME));
			values.put(TableUser.COLUMN_BALLANCE, object.getString(User.USER_BALLANCE));
			values.put(TableUser.COLUMN_EMAIL, object.getString(User.USER_EMAIL));
			values.put(TableUser.COLUMN_PHONE, object.getString(User.USER_PHONE));
			JSONArray accounts_array = object.getJSONArray(User.USER_ACCOUNTS);
			if (accounts_array.length() == 0) {
				values.put(TableUser.COLUMN_ACCOUNTS, "");
			} else {
				String accounts = "";
				for (int i = 0; i < accounts_array.length(); i++) {
					accounts += accounts_array.getString(i);
					if (i < accounts_array.length() - 1) {
						accounts += "|";
					}
				}
				values.put(TableUser.COLUMN_ACCOUNTS, accounts);
			}
			values.put(TableUser.COLUMN_DATE, "dare");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		context.getContentResolver().update(InfiniteContentProvider.CONTENT_URI_USERS, values, TableUser.COLUMN_ID + "=" + user_id, null);
	}

	public synchronized boolean addNews(ResponseObject responseObject) {
		JSONObject object = responseObject.getData();
		int user_id = App.getUser().getId();
		ContentValues[] values = null;
		try {
			JSONArray news = object.getJSONArray("news");
			values = new ContentValues[news.length()];
			for (int i = 0; i < news.length(); i++) {
				JSONObject o = news.getJSONObject(i);
				ContentValues v = new ContentValues();
				v.put(TableNews.COLUMN_USER_ID, user_id);
				v.put(TableNews.COLUMN_ID, o.getInt(NewsItem.NEWS_POST_ID));
				v.put(TableNews.COLUMN_TYPE, o.getString(NewsItem.NEWS_TYPE));
				v.put(TableNews.COLUMN_POSTER_ICON, o.getString(NewsItem.NEWS_AVATAR));
				v.put(TableNews.COLUMN_POSTER_NAME, o.getString(NewsItem.NEWS_AUTHOR_NAME));
				v.put(TableNews.COLUMN_POSTER_ID, o.getInt(NewsItem.NEWS_AUTHOR_ID));
				v.put(TableNews.COLUMN_POST_TEXT, o.getString(NewsItem.NEWS_POST_CONTENT));
				v.put(TableNews.COLUMN_POST_TITLE, o.getString(NewsItem.NEWS_POST_TYTLE));
				v.put(TableNews.COLUMN_DATE, o.getString(NewsItem.NEWS_POST_DATE));
				JSONArray imgs = o.getJSONArray(NewsItem.NEWS_POST_IMG);
				String imgs_str = "";
				if (imgs.length() == 0) {
					v.put(TableNews.COLUMN_POST_IMGS, imgs_str);
				} else {
					for (int j = 0; i < imgs.length(); j++) {
						imgs_str += imgs.getString(j);
						if (i < imgs.length() - 1) {
							imgs_str += "|";
						}
					}
					v.put(TableNews.COLUMN_POST_IMGS, imgs_str);
				}
				values[i] = v;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		int rows = context.getContentResolver().bulkInsert(InfiniteContentProvider.CONTENT_URI_NEWS, values);
		return rows>0;
	}
	
	public NewsItem getNewsItem(int position){
		String selection = TableNews.COLUMN_ID+"="+position;
		Cursor cursor = context.getContentResolver().query(InfiniteContentProvider.CONTENT_URI_NEWS, null, selection, null, null);
		if(cursor!=null && cursor.moveToFirst()){
			int id = cursor.getInt(cursor.getColumnIndex(TableNews.COLUMN_ID));
			String type= cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_TYPE));
			String poster_icon= cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_POSTER_ICON));
			String poster_name= cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_POSTER_NAME));
			int poster_id= cursor.getInt(cursor.getColumnIndex(TableNews.COLUMN_POSTER_ID));
			String post_title= cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_POST_TITLE));
			String post_text= cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_POST_TEXT));
			String imgs = cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_POST_IMGS));
			String[] post_imgs;
			if(!imgs.equals("")){
				post_imgs = imgs.split("\\|");
			}else{
				post_imgs = new String[]{};
			}
			String post_date= cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_DATE));
			return new NewsItem(id, type, poster_icon, poster_name, poster_id, post_title, post_text, post_imgs, post_date);
		}
		return null;
		
	}
	
	public synchronized boolean addTransactions(ResponseObject responseObject){
		JSONObject object = responseObject.getData();
		int user_id = App.getUser().getId();
		ContentValues[] values = null;
		try {
			JSONArray trans = object.getJSONArray("trans");
			values = new ContentValues[trans.length()];
			for (int i = 0; i < trans.length(); i++) {
				JSONObject o = trans.getJSONObject(i);
				ContentValues v = new ContentValues();
				v.put(TableTransaktions.COLUMN_USER_ID, user_id);
				v.put(TableTransaktions.COLUMN_ID, o.getInt(Transaktion.TRANS_ID));
				v.put(TableTransaktions.COLUMN_PARTNER_ID, o.getInt(Transaktion.TRANS_PARTNER_ID));
				v.put(TableTransaktions.COLUMN_PARTNER_NAME, o.getString(Transaktion.TRANS_BRANCH_NAME));
				v.put(TableTransaktions.COLUMN_BRANCH_ID, o.getInt(Transaktion.TRANS_BRANCH_ID));
				v.put(TableTransaktions.COLUMN_POS_IMEI, o.getString(Transaktion.TRANS_POS_IMEI));
				v.put(TableTransaktions.COLUMN_CARD_NUMBER, o.getString(Transaktion.TRANS_CARD_NUMBER));
				v.put(TableTransaktions.COLUMN_DATE, o.getString(Transaktion.TRANS_DATE));
				v.put(TableTransaktions.COLUMN_ACTION_TIPE, o.getInt(Transaktion.TRANS_ACTION_TYPE));
				v.put(TableTransaktions.COLUMN_CANCEL_ID, o.getInt(Transaktion.TRANS_CANCEL_ID));
				v.put(TableTransaktions.COLUMN_PAYMENT, o.getInt(Transaktion.TRANS_PAYMENT));
				v.put(TableTransaktions.COLUMN_CARD_TYPE, o.getInt(Transaktion.TRANS_CARD_TYPE));
				v.put(TableTransaktions.COLUMN_CARD_PERCENT, o.getInt(Transaktion.TRANS_CARD_PERCENT));
				v.put(TableTransaktions.COLUMN_BONUS, o.getInt(Transaktion.TRANS_BONUS));
				v.put(TableTransaktions.COLUMN_BALLANCE_BONUS, o.getInt(Transaktion.TRANS_BONUS_BALLANCE));
				v.put(TableTransaktions.COLUMN_FEE_PERCENT, o.getInt(Transaktion.TRANS_FEE_PERCENT));
				v.put(TableTransaktions.COLUMN_FEE, o.getInt(Transaktion.TRANS_FEE));
				v.put(TableTransaktions.COLUMN_FEE_BALANCE, o.getInt(Transaktion.TRANS_FEE_BALANCE));
				v.put(TableTransaktions.COLUMN_FEE_BALANCE, o.getInt(Transaktion.TRANS_FEE_BALANCE));
				v.put(TableTransaktions.COLUMN_COMMENT, o.getString(Transaktion.TRANS_COMMENT));
				v.put(TableTransaktions.COLUMN_STATUS, o.getInt(Transaktion.TRANS_STATUS));
				
				values[i] = v;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		int rows = context.getContentResolver().bulkInsert(InfiniteContentProvider.CONTENT_URI_TRANSAKTIONS, values);
		return rows>0;
	}

}
